<template>
    <div class="add">
      <el-card class="box-card">
        <span><b>录入题目</b></span>
        <el-form :model="state.questionForm" :rules="state.rules" ref="questionRef" label-width="80px">
          <el-form-item label="题目：" prop="content">             
          <!-- 这里放富文本框 -->
          <div style="width:800px">
            <Editor v-model="state.questionForm.content" @input="(val)=> {state.questionForm.content=val}"></Editor>
          </div>  
          </el-form-item>       
          <!-- 上传题目图片 -->
          <el-form-item label="插图" prop="images">      
            <UploadImage ref="uploadImage_content" :limit="5" :action="state.uploadImgServer" :father_method="getImageList"></UploadImage>   
          </el-form-item>
            <el-form-item label="知识点：" prop="knowledgepoint">
              <el-select v-model="state.questionForm.knowledgepoint" size="small" class="m-2">
                <el-option
                  v-for="item in knowledgepointOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>

          <el-form-item label="答案：" prop="answer">
            <el-input style="width: 500px" v-model="state.questionForm.answer" placeholder="请输入参考答案" clearable></el-input>
          </el-form-item>
          <el-form-item label="插图：">
            <UploadImage ref="uploadImage_answer" :limit="8" :fileList="state.fileList_answer" :action="state.uploadImgServer" :father_method="getImageList_answer"></UploadImage>
          </el-form-item>
          <el-form-item label="解析：" prop="explain">
            <el-input v-model="state.questionForm.explain" placeholder="解析：" clearable></el-input>
          </el-form-item>         
          <!-- 上传解析插图 -->
          <el-form-item label="插图：">
            <UploadImage ref="uploadImage_explain" :limit="8" :fileList="state.fileList_explain" :action="state.uploadImgServer" :father_method="getImageList_explain"></UploadImage>
          </el-form-item>

          <el-form-item label="来自：" prop="reference">
            <el-input style="width: 300px" v-model="state.questionForm.reference" placeholder="来自什么资料" clearable></el-input>
          </el-form-item>
          
          <el-form-item label="题型：" prop="type">
            <el-select v-model="state.questionForm.type" class="m-2" placeholder="题型" size="small">
              <el-option
                v-for="item in questionTypeOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>            
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty_level">            
            <el-select v-model="state.questionForm.difficulty_level" class="m-2" placeholder="难度：" size="small">
              <el-option
                v-for="item in difficultyLevelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="公开：" prop="open_level">
            <el-select v-model="state.questionForm.open_level" class="m-2" placeholder="公开/私密" size="small">
              <el-option
                v-for="item in openLevelOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>             
          </el-form-item> 
          <el-form-item>
            <el-button type="primary" @click="submitAddOneQuestion">提交</el-button> 
          </el-form-item>
        </el-form>  
                
        
      </el-card>      
    </div>
</template>


<script setup>
import Editor from '@/components/TinymceEditor.vue';
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { reactive, ref, toRefs, onMounted, watch, onBeforeMount, onUnmounted,computed, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, convertQuestionFormat } from '@/utils'
import { useStore } from 'vuex'
import UploadImage from '@/components/UploadImage.vue';


const uploadPictureRef=ref(null)
const uploadPictureExplainRef=ref(null)
const store=useStore()
const editor = ref(null) // 富文本编辑器 ref
const questionRef = ref(null)
const route = useRoute()
const router = useRouter()
const knowledgepointOption = reactive([])


const questionTypeOption = [
  {
    value : 1,
    label : '选择题',
  },
  {
    value : 2,
    label : '填空题',
  },
  //   {
  //   value : 0,
  //   label : '简答题',
  // },
]
const difficultyLevelOption = [
{
    value : 1,
    label : '入门',
  },
  {
    value : 2,
    label : '中级',
  },
  {
    value : 3,
    label : '较难',
  },
  {
    value : 4,
    label : '高级',
  },
  {
    value : 5,
    label : '压轴',
  },
]
const openLevelOption = [
  {
    value : 'public',
    label : '所有人可见',
  },
  {
    value : 'private',
    label : '仅自己可见',
  },
  // {
  //   value : 'friend',
  //   label : '好友可见',
  // },
]
const validateKnowledgepoint = (rule, value, callback) => {
  if (value<0) {
    callback(new Error('没有选择知识点'))
  }else {
    callback()
  }
}
const state = reactive({
  visible: false,   //控制本组件的弹窗是否可视
  uploadImgServer, // 上传图片的接口地址，单图上传
  token: localGet('token') || '', // 存在本地的 token
  pictures: "",
  fileList_answer:[],
  fileList_explain:[],
  questionForm:{          //题目表单 
    content: "请输入题目内容",         
    answer: "",
    images:[],            //题目题干插图
    explain: "",
    images_explain:[],
    reference: "",
    type: 1,
    difficulty_level: 1, 
    open_level: "public",
    knowledgepoint: -1,
    knowledgepoint_cn: "",
  },
  
  rules: { // 规则
    content: [
      {required: 'true', message: '请填写题目内容', trigger: ['change']}
    ],
    knowledgepoint: [
      {required: 'true', message: '请选择知识点', trigger: ['change']},
      {validator: validateKnowledgepoint, trigger: 'blur'}
    ],
    answer: [
      { required: 'true', message: '请填写参考答案', trigger: ['change'] }
    ],
    explain: [
      { required: 'true', message: '请填写解析', trigger: ['change'] }
    ],
    type: [
      { required: 'true', message: '请选择题型', trigger: ['change'] }
    ],
    difficulty_level: [
      { required: 'true', message: '请选择难度', trigger: ['change'] }
    ],    
  },
})

onMounted(() => {
  getChoiceList() 
})
const initQuestion=()=>{
  state.questionForm={          //题目表单  
    content: "可以直接从word复制过来",
    answer: "",
    explain: "",
    pictures: "",         //跟数据表中对应的字段内容
    images:[],    
    pictures_explain: "",   //同上 
    images_explain:[],
    reference: "",
    type: 1,
    difficulty_level: 2, 
    open_level: "private",
    knowledgepoint: -1,
  }
}
// 提交表单
const submitAddOneQuestion = () => {
  console.log("我要提交表单啦：",state.questionForm)
  state.questionForm = converQuestionFormat(state.questionForm)
  questionRef.value.validate((vaild, obj) => {
    if (vaild) { 
      var re = /<br>/g
      let params = {                    
          content: state.questionForm.content,
          pictures: state.questionForm.pictures,
          answer: state.questionForm.answer,
          explain: state.questionForm.explain,
          pictures_explain: state.questionForm.pictures_explain,
          pictures_answer: state.questionForm.pictures_answer,
          reference: state.questionForm.reference,
          type: state.questionForm.type,
          difficulty_level: state.questionForm.difficulty_level,
          knowledgepoint: state.questionForm.knowledgepoint,
          open_level: state.questionForm.open_level,          
        }
      axios.post('/questions/', params).then((result) => {
        if(result.code==200){
          ElMessage.success( '操作成功！')
          var r=confirm("录入题目成功。取消继续录入，确定返回首页!");
            if (r==true){
                router.push("/")
            }else{
              initQuestion()
            }
        }else{
          console.log("提交错误", result.message)
        }       
      })
    }else{
      ElMessage.success( '表单没有通过！')      
      for (let key in obj) {
        console.log("具体原因是：", obj[key][0].message)
        return false;
      }   
    }
  })
}
// 从后台读取知识点列表
const getChoiceList =()=>{
  axios.get(`/knowledgepoints?size=100`).then(res =>{
    if (res.code == 200){
      const temp_list = res.data.results
      knowledgepointOption.splice(0)
      for (let i=0; i<temp_list.length; i++){
        knowledgepointOption.push({value:temp_list[i].id, label:temp_list[i].name})
      } 
    }else{
      console.log("error", data.message)
    }
  }) 
}
// 子组件upload传过来的图片数组
const getImageList=(list)=>{
    console.log("upload子组件传过来的",list)
    state.questionForm.images.splice(0,state.questionForm.images.length)
    for(let item of list){
      state.questionForm.images.push(item.url)
    }
    console.log("edit的images",state.questionForm.images)
  }
  // 子组件upload传过来的解析图片数组
  const getImageList_explain=(list)=>{
    console.log("upload子组件传过来的",list)
    state.questionForm.images_explain.splice(0,state.questionForm.images.length)
    for(let item of list){
      state.questionForm.images_explain.push(item.url)
    }
  }
  // 子组件upload传过来的解析图片数组
  const getImageList_answer=(list)=>{
    console.log("upload子组件传过来的",list)
    state.questionForm.images_answer.splice(0,state.questionForm.images_answer.length)
    for(let item of list){
      state.questionForm.images_answer.push(item.url)
    }
  }
//打开弹窗
const open = (knowledgepointId) => {
  if(knowledgepointId & knowledgepointId>=0){
    state.questionForm.knowledgepoint = knowledgepointId    
  }
  state.visible = true
};
// 关闭弹窗
const close = () => {
  state.visible = false
};

defineExpose({ open, close })
</script>


<style scoped>
  .add{
    width: 1000px;
  }
  .questionForm{
    width: 900px;
  }
  .box-card{
    width: 950px;
  }
</style>